import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { getLocal } from '@/utils/local.js'
import { myInfo } from '@/api/my.js'

Vue.use(VueRouter)

const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/login'
  },
  // 配置路由   路由懒加载
  // 登陆页面
  {
    path: '/login',
    component: () => import('@/views/login/login.vue')
  },
  // home页面
  {
    path: '/home',
    component: () => import('@/views/home/home.vue'),
    children: [
      // 我的页面
      {
        path: '/home/my',
        component: () => import('@/views/home/my/my.vue'),
        meta: {
          showTabbar: true,
          needToken: true
        }
      },
      // 数据页面
      {
        path: '/home/date',
        component: () => import('@/views/home/date/date.vue'),
        meta: {
          showTabbar: true
        }
      },
      // 比赛页面
      {
        path: '/home/play',
        component: () => import('@/views/home/play/play.vue'),
        meta: {
          showTabbar: true
        }
      },
      // 主播页面
      {
        path: '/home/bost',
        component: () => import('@/views/home/bost/bost.vue'),
        meta: {
          showTabbar: true
        }
      },
      // 发现页面
      {
        path: '/home/find',
        component: () => import('@/views/home/find/index.vue'),
        redirect: '/home/find/find',
        meta: {
          showTabbar: true
        },
        children: [
          {
            path: 'community',
            component: () => import('@/views/home/find/community.vue'),
            meta: {
              showTabbar: true
            }
          },
          {
            path: 'find',
            component: () => import('@/views/home/find/find.vue'),
            meta: {
              showTabbar: true
            }
          },
          {
            path: 'highlight',
            component: () => import('@/views/home/find/highlight.vue'),
            meta: {
              showTabbar: true
            }
          }
        ]
      },
      // 详情
      {
        path: '/home/headline',
        component: () => import('@/views/home/headline/headline.vue'),
        meta: {
          // showTabbar: true
          detailTabbar: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  //  判断是否需要登陆
  //    不需要  next
  //    需要
  //      看看有没登陆
  //         没登陆
  //            有token:获取用户信息后再net
  //            没有token:跳转到登陆页
  //         有登陆   next
  if (!to.meta.needToken) {
    next()
  } else {
    if (store.state.isLogin) {
      next()
    } else {
      if (getLocal('token')) {
        myInfo({ userId: getLocal('userId') }).then(res => {
          store.commit('setUserInfo', res.data.data)
          // 设置登录状态   登录成功获取个人信息,保存到vuex中然后然后设置登录状态
          store.commit('setIsLogin', true)
          next()
        })
      } else {
        next('/login')
      }
    }
  }
})

export default router
